package pers.lolicer.redtidelibrary.utils

import AppColor
import android.content.Context
import android.graphics.Bitmap
import android.graphics.pdf.PdfRenderer
import android.net.Uri
import android.util.Log
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.toArgb
import pers.lolicer.redtidelibrary.R
import pers.lolicer.redtidelibrary.config.BitmapImageConfig

class PdfUtils {
    // 获取PDF的封面，PDF不存在则返回“文件不存在”的封面
    fun getPdfCoverFromUri(context: Context, contentUri: Uri): ImageBitmap {
        try {
            val fileDescriptor = context.contentResolver.openFileDescriptor(contentUri, "r")

            if(fileDescriptor == null){
                Log.d("pdf1", "")
                return BitmapImageConfig.createBitmap(context, R.drawable.type_err)
            }
            else{
                val pdfRenderer = PdfRenderer(fileDescriptor)
                val coverPage = pdfRenderer.openPage(0)
                val bitmap = Bitmap.createBitmap(
                    coverPage.width,
                    coverPage.height,
                    Bitmap.Config.ARGB_8888
                )

                // 对于透明背景的PDF，要渲染背景颜色
                val canvas = android.graphics.Canvas(bitmap)
                canvas.drawColor(AppColor.CoverBackground(context).toArgb())

                coverPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT)

                fileDescriptor.close()
                coverPage.close()
                pdfRenderer.close()

                Log.d("pdf2", "")
                return bitmap.trimToA4Size().asImageBitmap()
            }
        }
        catch (e: SecurityException){
            e.printStackTrace()
            Log.d("pdf3", "")
            return BitmapImageConfig.createBitmap(context, R.drawable.type_err)
        }
    }
}